<script setup lang="ts">
import { ButtonProps, ElLoading } from 'element-plus';
import { ModalForm, OptionalMutable } from '../types';
import { computed, Ref, ref } from 'vue';
import { callFunc, genKey } from '../base';

const visible = ref(true)

const cls = `ui-dialog-${genKey()}`

const actions = {
  close () {
    visible.value = false
  },
  showLoading () {
    return ElLoading.service({
      target: document.querySelector(`.${cls}`) as HTMLElement
    })
  }
}

type Btn = OptionalMutable<ButtonProps> & {
  label?: string,
  action?: (dialog: typeof actions) => any
}

const props = defineProps<{
  btns?: Btn[],
  slotRef?: Ref<ModalForm | undefined>
}>()

const emit = defineEmits<{
  submitted: [e?: any]
}>()

const onOk = async () => {
  const formRef = props.slotRef?.value
  await callFunc(formRef?.validate)
  const loading = actions.showLoading()
  try {
    await callFunc(formRef?.submit)
    emit('submitted')
    actions.close()
  } finally {
    loading.close()
  }
}

const btns = computed<Btn[]>(() => {
  return props.btns ?? [
    { type: 'primary', label: '确定', action: onOk },
    { label: '取消', action: actions.close }
  ]
})

const onBtnClick = (btn: Btn) => callFunc(btn.action, actions)
</script>

<template>
  <ElDialog :class="cls" v-model="visible">
    <slot></slot>
    <template #footer>
      <ElButton v-for="(btn, i) in btns" :key="i" v-bind="btn" @click="onBtnClick(btn)">
        {{ btn.label }}
      </ElButton>
    </template>
  </ElDialog>
</template>
